package com.jk.aop;

import com.alibaba.fastjson.JSON;
import com.jk.model.LogBean;
import com.jk.common.CommonConf;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Aspect
@Component
public class LogAop {

    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Pointcut(value = "execution(* com.jk.controller.*.*(..))")
    public void logCut(){}

    @AfterReturning(pointcut="logCut()",returning="obj")
    public void saveLog(JoinPoint joinpoint, Object obj) {
        System.out.println("存储日志");
        LogBean logBean = new LogBean();
        //获取类名
        String methodName = joinpoint.getSignature().getName();
        //获取方法名
        String className = joinpoint.getTarget().getClass().getSimpleName();
        Object[] args = joinpoint.getArgs();
        //响应参数
        StringBuffer requestParams = new StringBuffer();
        for (int i = 0; i < args.length; i++) {
            requestParams.append("第"+i+"个参数=").append(args[i]);
        }
        //返回参数
        String responseParams=obj==null ? "" :obj.toString();
        logBean.setClassName(className);
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(currentTime);
        logBean.setCreateTime(dateString);
        logBean.setMethodName(methodName);
        logBean.setRequestParams(requestParams.toString());
        logBean.setResponseParams(responseParams);
        String jsonString = JSON.toJSONString(logBean);
        //发送消息到kafka中
        kafkaTemplate.send(CommonConf.LOG_TOPIC,jsonString);

    }
}
